<?php
/**
 * User: @lose
 * Date: 2019-10-23
 * Time: 16:59
 */

namespace Beerus\Modules\Album\Controllers;

use App\Admin\Extensions\Tools\GridView;
use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\model\Album\AlbumListModel;
use Biz\model\Album\AlbumRelateTagsModel;
use Biz\model\Album\AlbumWikiListModel;
use Biz\service\Album\AlbumCategoryService;
use Biz\service\Album\AlbumListService;
use Biz\service\Album\AlbumTagListService;
use Doraemon\cache\AlbumCounter;
use Doraemon\amqp\CommunityQueue;
use Doraemon\tools\PointConfig;
use Doraemon\model\Sysmsg;
use Doraemon\tools\HhzEnv;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\IdParse;
use Doraemon\tools\LinkFormat;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;


class AlbumCheckController extends Controller
{
    const PAGE_SIZE = 20;

    public function index(Request $request, Content $content)
    {
        $params = $request->all();
        $where = $this->getCondition($params);
        $search_params = http_build_query($params);
        $albumList = AlbumListModel::selectByWhere($where);
        unset($where['ORDER']);
        unset($where['LIMIT']);
        $total = AlbumListModel::count($where);
        $albumIds = array_column($albumList, 'album_id');
        //获取内容的标签
        $contentLabel = [];
        $AlbumCounters = [];
        if ($albumIds) {
            $contentLabel = AlbumTagListService::getLabelByIds($albumIds);
            $AlbumCounters = AlbumCounter::getMulti($albumIds);
        }
        foreach ($albumList as &$val) {
            $val['publish_time'] = date("Y-m-d H:i:s", $val['publish_time']);
        }

        $options = [
            'perPage' => $request->input('per_page') ?: 20,
        ];
        //查询标签列表
        $tagList = AlbumListService::getTagList();
        $tagArr = [];
        if ($tagList) {
            foreach ($tagList as $tag) {
                $tagArr[] = explode('|', $tag)[1];
            }
        }
        $gridModel = new pGridDataModel($albumList, $total, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $contentLabel, $AlbumCounters, $tagArr, $search_params) {
            $grid->paginate($gridModel->getPerPage());
            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            $grid->disableActions();
            $grid->tools(function ($tools) use ($search_params) {
                $tools->append(new GridView());
                $tools->append('<div class="btn-group" style="margin-right: 10px">
<a class="btn btn-sm btn-twitter" title="导出下载" href="' . url('/admin/album/albumcheck/export?' . $search_params) . '" target="_blank">
<i class="fa fa-download"></i><span class="hidden-xs">导出/下载</span></a></div>');
            });

            $grid->filter(function (\Encore\Admin\Grid\Filter $filter) use ($tagArr) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('Find', [
                        'album_id' => '清单id',
                        'uid' => 'uid',
                        'title' => "清单标题",
                    ]);
                    $filter->equal('wiki_id', '商品id');
                    $filter->equal('score', '分数')->checkbox(AlbumListModel::SCORE_MAP);
                    $filter->equal('audit_status', '审核状态')->radio(AlbumListModel::ADM_STATUS_MAP)->default(0);
                });
                $filter->column(1 / 2, function ($filter) use ($tagArr) {
                    $filter->between('publish_time', '发布时间')->datetime();
                    $filter->equal('tag_name', '标签')->select(array_combine($tagArr, $tagArr));
                });
                //条件展开
                $filter->expand();
            });
            $grid->column('album_id', '清单id')->width(100);
            $grid->column('uid', '用户信息')->userBasicInfo()->width(150);
            $grid->column('score', '额外信息')->display(function () {
                $url = Hhzurl::getAlbumH5Link($this->album_id, 1);
                return "<br><a href='{$url}' target='_blank'  >清单详情</a><br><br><a href='javascript:;' class='btn btn-default copyH5'  data-id='{$this->album_id}' >复制链接</a>";
            });

            $grid->column('addtime', '清单信息')->display(function () {
                return "<img src='{$this->cover_img}' width=100 /><br/><strong>[标题]:</strong>{$this->title}<br><strong>[描述]:</strong><br/>{$this->desc}<br><strong>[商品数量]:</strong><br/>{$this->wiki_count}";
            });
            $grid->column('admin_tag', '交互')->display(function () use ($AlbumCounters) {
                return "<strong>[评论]:</strong>{$AlbumCounters[$this->album_id]['comment']}<br><strong>[点赞]:</strong>{$AlbumCounters[$this->album_id]['like']}<br><strong>[收藏]:</strong>{$AlbumCounters[$this->album_id]['favorite']}<br>";
            })->width(100);
            $grid->column('publish_time', '发布时间');
            $grid->column('edittime', '更新时间');
            $grid->column('content_label', '打标签')->display(function () use ($contentLabel) {
                $dataId = isset($contentLabel[$this->album_id]) ? $contentLabel[$this->album_id] : [];
                $dataId = json_encode($dataId);
                return "<div id={$this->album_id} class='content-label' data-id={$dataId}></div>";
            })->width(350);
            $grid->column("quality", '打分')->display(function () {

                if ($this->status == AlbumListModel::STATUS_USER_PRIVATE) {
                    return '';
                }
                if ($this->score == 60) {
                    $commonBtn = "<a href='javascript:;' class='btn btn-success setQuality'  data-id='$this->album_id' id='common$this->album_id' data-score='60' data-quality='common'>普通</a>";
                } else {
                    $commonBtn = "<a href='javascript:;' class='btn btn-default setQuality'  data-id='$this->album_id' id='common$this->album_id' data-score='60' data-quality='common'>普通</a>";
                }

                if ($this->score == 5) {
                    $badBtn = "<a href='javascript:;' class='btn btn-success setQuality'  data-id='$this->album_id' id='bad$this->album_id' data-score='5' data-quality='bad'>差</a>";
                } else {
                    $badBtn = "<a href='javascript:;' class='btn btn-default setQuality'  data-id='$this->album_id' id='bad$this->album_id' data-score='5' data-quality='bad'>差</a>";
                }

                if ($this->score == 70) {
                    $goodBtn = "<a href='javascript:;' class='btn btn-success setQuality'  data-id='$this->album_id' id='good$this->album_id' data-score='70' data-quality='good'>优质</a>";
                } else {
                    $goodBtn = "<a href='javascript:;' class='btn btn-default setQuality'  data-id='$this->album_id' id='good$this->album_id' data-score='70' data-quality='good'>优质</a>";
                }

                if ($this->score == 80) {
                    $excellentBtn = "<a href='javascript:;' class='btn btn-success setQuality'  data-id='$this->album_id' id='excellent$this->album_id' data-score='80' data-quality='excellent'>精选</a>";
                } else {
                    $excellentBtn = "<a href='javascript:;' class='btn btn-default setQuality'  data-id='$this->album_id' id='excellent$this->album_id' data-score='80' data-quality='excellent'>精选</a>";
                }

                if ($this->status == AlbumListModel::STATUS_PRIVATE) {
                    $privateBtn = "<a href='javascript:;' class='btn btn-success setQuality'  data-id='$this->album_id' id='private$this->album_id' data-score='0' data-quality='private'>仅自己可见</a>";
                } else {
                    $privateBtn = "<a href='javascript:;' class='btn btn-default setQuality'  data-id='$this->album_id' id='private$this->album_id' data-score='0' data-quality='private'>仅自己可见</a>";
                }

                return $commonBtn . "<br/><br/>" . $badBtn . "<br/><br/>" . $goodBtn . "<br/><br/>" . $excellentBtn . "<br/><br/>" . $privateBtn;
            })->width(150);
            $grid->column("status", '状态')->display(function () {
                if ($this->status == AlbumListModel::STATUS_SUCCESS) {
                    $commonBtn = "<a href='javascript:;' class='btn btn-info' id='btnStatus$this->album_id' >已审核</a>";
                }
                if ($this->status == AlbumListModel::STATUS_WAIT_CHECK) {
                    $commonBtn = "<a href='javascript:;' class='btn btn-default' id='btnStatus$this->album_id' >待复审</a>";
                }
                if ($this->status == AlbumListModel::STATUS_UNTREATED) {
                    $commonBtn = "<a href='javascript:;' class='btn btn-default' id='btnStatus$this->album_id' >待审核</a>";
                }
                if ($this->status == AlbumListModel::STATUS_PRIVATE) {
                    $commonBtn = "<a href='javascript:;' class='btn btn-warning' id='btnStatus$this->album_id' >仅自己可见</a>";
                }
                if ($this->status == AlbumListModel::STATUS_USER_PRIVATE) {
                    $commonBtn = "<a href='javascript:;' class='btn btn-warning' id='btnStatus$this->album_id' >用户私密状态</a>";

                }
                return $commonBtn;
            })->width(150);


        });
        Admin::script($this->labelScript());
        Admin::script($this->adminScore());


        return $content
            ->header('清单审核')
            ->body($listGrid);

    }

    //获取所有的内容标签
    public function labelList()
    {
        $data = AlbumTagListService::getListFormat();
        return response()->json([
            'code' => 1,
            'data' => $data
        ]);
    }

    //内容标签的修改
    public function labelSubmit(Request $request)
    {
        $param = $request->all();
        $noteId = $param['note_id'] ?? 0;
        $firstId = $param['first_id'] ?? 0;
        $secondId = $param['second_id'] ?? [];

        if (empty($noteId) || empty($firstId)) {
            return response()->json([
                'code' => 0,
                'msg' => '参数不能为空'
            ]);
        }
        $result = AlbumTagListService::changeAlbumLabel($noteId, $firstId, $secondId, Admin::user()->id);

        //更新清单标签时  同步修改 清单分类关系表
        AlbumCategoryService::saveAlbumToCategory($noteId);

        AlbumListService::setTopcCache();//生成缓存

        return response()->json([
            'code' => 1,
            'msg' => 'ok',
            'data' => $result
        ]);
    }


    private function labelScript()
    {
        $prefix = request()->url();
        return <<<SCRIPT
function loadScript(src, callback) {  
var script = document.createElement("script");  
  
if(script.addEventListener)  
script.addEventListener("load", callback, false);  
else if(script.attachEvent)  
script.attachEvent("onreadystatechange",  
function() { loadScript.callbackIE(callback); });  
  
script.src = src;  
document.getElementsByTagName("head")[0].appendChild(script);  
}  
loadScript.callbackIE = function(callback) {  
var target = window.event.srcElement;  
if(target.readyState == "loaded")  
callback.call(target);  
};  
  
// load 30k script.  
// Listener.cleanUp is defined at the bottom of drag.js  
callback = function() {  

notePicTag.init({
            selectRequestUrl: '{$prefix}/content/labelList',
            submitRequestUrl: '{$prefix}/content/labelSubmit',
//            rootObjId:'content-label'
            rootNodeId: 'content-label'
        }); 
}; 
loadScript("/vendor/js/frieza-fe/notePicTag.js", callback);
SCRIPT;
    }


    /**
     * @param $album_id
     * @param $type
     * @param $score
     * @return \Illuminate\Http\JsonResponse
     */
    public function editScore($album_id, $type, $score)
    {
        $data = [
            'quality' => AlbumListModel::SCORE_QUALITY_MAP[$score],
            'score' => $score,
        ];
        if ($score == 0) {
            $data['status'] = AlbumListModel::STATUS_PRIVATE;
        } else {
            $data['status'] = AlbumListModel::STATUS_SUCCESS;
        }
        //这里要提前查询清单基本信息 更新用户成长值需要old_quality
        $albumInfo = AlbumListService::getAlbumListCache([$album_id])[$album_id] ?? [];
        if ($type == "add") {
            $rs = AlbumListModel::update($data, [
                'album_id' => $album_id,
            ]);
        }
        $status = $data['status'];
        if ($rs) {
            AlbumListService::setTopcCache();//生成缓存
            $quality = AlbumListModel::SCORE_QUALITY_MAP[$score];
            if (AlbumListModel::QUALITY_EXCELLENT == $quality) {//精选发系统消息
                $info = AlbumListModel::getAlbumById($album_id);
                $info = AlbumListModel::formatInfo($info);
                $uid = IdParse::getUid($album_id);
                if ($uid && $info['cover_img_url']) {
                    $picList = [
                        $info['cover_img_url'], // 用户首图
                        'https://img.haohaozhu.cn/Op-imageShow/8e19d308y04j0Qd00qs07h4?iv=1'// 盖章
                    ];
                    $tid = 52;//线上模版id
                    if (HhzEnv::isTest()) {
                        $tid = 18;
                    }
                    $result = \Doraemon\tools\ImageCreate::buildImageByTidAndParams($tid, $picList);
                    $picUrl = $result['url'];
                    \Doraemon\cache\Queue::insertQueue('queue/Sysmsg/Send',
                        [
                            'msgCode' => 0,
                            'to_uid' => $uid,
                            'msgParams' => [
                                'title' => '',
                                'detail' => '你的好物清单被评为精选啦！持续分享让更多住友看到你的好眼光～',
                                'img' => $picUrl,
                                'link' => Hhzurl::getAlbumDetailNiceLivingLink($album_id),
                                'type' => Sysmsg::TYPE_SYS_MSG,
                            ]
                        ],
                        \Doraemon\cache\Queue::QUEUE_DORAEMON);
                }

                //清单置为精选的时候加积分（只加一次，振兴那会控制）
                CommunityQueue::insertQueue(PointConfig::MQ_QUEUE_URL, [
                    'event_name' => PointConfig::ALBUM_QUALITY_FEATURED,
                    'obj_id' => $album_id,//清单id
                    'uid' => $uid,//用户的uid
                    'type' => PointConfig::POINT_AWARD,
                ], CommunityQueue::QUEUE_COMMUNITY);
            }

            //这里要查询清单商品信息 更新用户成长值需要
            $wikiIds = AlbumWikiListModel::selectByWhere(['album_id'=>$album_id,'status'=>AlbumWikiListModel::STATUS_NORMAL],'wiki_id');

            //更新用户成长值
            $remarks = ['old_quality' => $albumInfo['quality'] ?? 0, 'new_quality' => AlbumListModel::SCORE_QUALITY_MAP[$score] ?? 0, 'new_wiki_id' => $wikiIds,'old_wiki_id' => []];
            \Doraemon\amqp\CommunityQueue::insertQueue(\Doraemon\tools\Creator\GrowthConfig::MQ_QUEUE_URL, [
                'event_name' => \Doraemon\tools\Creator\GrowthConfig::GROWTH_ALBUM_LIST_CHECK,
                'obj_id' => $album_id,
                'uid' => $albumInfo['uid'] ?? 0,
                'remarks' => json_encode($remarks, JSON_UNESCAPED_UNICODE),
            ], \Doraemon\amqp\CommunityQueue::QUEUE_COMMUNITY);
            $result = true;
            $message = "操作成功";
        } else {
            $result = false;
            $message = "操作失败";
        }
        return response()->json(compact('result', 'status', 'message'));
    }

    //复制H5链接
    public function copyUrl($album_id)
    {
        return Hhzurl::getAlbumH5Link($album_id, 1);
    }


    public function adminScore()
    {
        return <<<SCRIPT
          $('.copyH5').click(function() {
            var id = $(this).data('id');
            $.ajax({type:"get",url:"albumcheck/copy/"+id,success:function(url){
            var tempInput = document.createElement("input");
            tempInput.value = url;
            document.body.appendChild(tempInput);
            tempInput.select();
            document.execCommand("copy");
            document.body.removeChild(tempInput);
            }});
        });
        $('.setQuality').click(function() {
                var id = $(this).data('id');
                var score = $(this).data('score');
                var quality = $(this).data('quality');
                console.log($(this).hasClass('setQuality'));

                    type = 'add';
                $.ajax({type:"get",url:"quality/"+id+"/"+type+"/"+score,success:function(data){
                console.log(data);
                    if(data.result==true) {
                        var status=data.status;
                        $('#'+quality+id).addClass('btn-success');
                        $('#'+quality+id).css('color','#FFFFFF');
                       if(quality == "common"){
                            $('#good'+id).removeClass('btn-success');
                            $('#good'+id).addClass('btn-default');
                            $('#good'+id).css('color','#444');
                            $('#bad'+id).removeClass('btn-success');
                            $('#bad'+id).addClass('btn-default');
                            $('#bad'+id).css('color','#444');
                            $('#excellent'+id).removeClass('btn-success');
                            $('#excellent'+id).addClass('btn-default');
                            $('#excellent'+id).css('color','#444'); 
                            $('#private'+id).removeClass('btn-success');
                            $('#private'+id).addClass('btn-default');
                            $('#private'+id).css('color','#444');   
                        }
                        
                       if(quality == "private"){
                            $('#good'+id).removeClass('btn-success');
                            $('#good'+id).addClass('btn-default');
                            $('#good'+id).css('color','#444');
                            $('#bad'+id).removeClass('btn-success');
                            $('#bad'+id).addClass('btn-default');
                            $('#bad'+id).css('color','#444');
                            $('#excellent'+id).removeClass('btn-success');
                            $('#excellent'+id).addClass('btn-default');
                            $('#excellent'+id).css('color','#444'); 
                            $('#common'+id).removeClass('btn-success');
                            $('#common'+id).addClass('btn-default');
                            $('#common'+id).css('color','#444');
                      
                        }
                        
                       if(quality == "bad"){
                            $('#good'+id).removeClass('btn-success');
                            $('#good'+id).addClass('btn-default');
                            $('#good'+id).css('color','#444');
                            $('#common'+id).removeClass('btn-success');
                            $('#common'+id).addClass('btn-default');
                            $('#common'+id).css('color','#444');
                            $('#excellent'+id).removeClass('btn-success');
                            $('#excellent'+id).addClass('btn-default');
                            $('#excellent'+id).css('color','#444');
                            $('#private'+id).removeClass('btn-success');
                            $('#private'+id).addClass('btn-default');
                            $('#private'+id).css('color','#444');    
                       }
                       if(quality == "good"){
                            $('#bad'+id).removeClass('btn-success');
                            $('#bad'+id).addClass('btn-default');
                            $('#bad'+id).css('color','#444');
                            $('#common'+id).removeClass('btn-success');
                            $('#common'+id).addClass('btn-default');
                            $('#common'+id).css('color','#444');
                            $('#excellent'+id).removeClass('btn-success');
                            $('#excellent'+id).addClass('btn-default');
                            $('#excellent'+id).css('color','#444');  
                            $('#private'+id).removeClass('btn-success');
                            $('#private'+id).addClass('btn-default');
                            $('#private'+id).css('color','#444');  
                       }
                       
                       if(quality == "excellent"){
                            $('#bad'+id).removeClass('btn-success');
                            $('#bad'+id).addClass('btn-default');
                            $('#bad'+id).css('color','#444');
                            $('#common'+id).removeClass('btn-success');
                            $('#common'+id).addClass('btn-default');
                            $('#common'+id).css('color','#444');
                            $('#good'+id).removeClass('btn-success');
                            $('#good'+id).addClass('btn-default');
                            $('#good'+id).css('color','#444');  
                            $('#private'+id).removeClass('btn-success');
                            $('#private'+id).addClass('btn-default');
                            $('#private'+id).css('color','#444');  
                       }  
                       if(status==1){
                        if( $('#btnStatus'+id).hasClass('btn-default')){
                            $('#btnStatus'+id).removeClass('btn-default');
                        }
                        if( $('#btnStatus'+id).hasClass('btn-warning')){
                            $('#btnStatus'+id).removeClass('btn-warning');
                        }
                        $('#btnStatus'+id).addClass('btn-info');
                        $('#btnStatus'+id).text('已审核');
                       }else if(status==11){
                        if( $('#btnStatus'+id).hasClass('btn-default')){
                            $('#btnStatus'+id).removeClass('btn-default');
                        }
                        if( $('#btnStatus'+id).hasClass('btn-info')){
                            $('#btnStatus'+id).removeClass('btn-info');
                        }
                        $('#btnStatus'+id).addClass('btn-warning');
                        $('#btnStatus'+id).text('仅自己可见');
                       }
//                       layer.msg('修改成功');
//                       setTimeout(function () {
//                           parent.window.location.reload();
//                        }, 2000);
                         toastr.success('修改成功', null, {
                            timeOut : 1000
                        });  
                    }else{
                     toastr.success('修改失败', null, {
                            timeOut : 1000
                        });
                    }
                }});
            });
            
  
SCRIPT;
    }


    //note详情页
    public function detail(Request $request, Content $content, $id)
    {
        $request = $request->all();
        return $content
            ->header('note详情')
            ->body($this->listDetail($request, $id));
    }

    /**
     * 导出
     */
    public function export(Request $request)
    {
        try {
            $params = $request->all();
            $params['page'] = 1;
            $params['per_page'] = 5000;
            $where = $this->getCondition($params);
            $albumList = AlbumListModel::selectByWhere($where);
            $albumIds = array_column($albumList, 'album_id');
            $AlbumCounters = [];
            if ($albumIds) {
                $AlbumCounters = AlbumCounter::getMulti($albumIds);
                $sheetData = [
                    ['cell_title' => '清单ID', 'cell_key' => 'A', 'cell_width' => 16, 'value_key' => 'album_id'],
                    ['cell_title' => '清单标题', 'cell_key' => 'B', 'cell_width' => 30, 'value_key' => 'title'],
                    ['cell_title' => '链接', 'cell_key' => 'C', 'cell_width' => 15, 'value_key' => 'link'],
                    ['cell_title' => 'uid', 'cell_key' => 'D', 'cell_width' => 15, 'value_key' => 'uid'],
                    ['cell_title' => '商品数', 'cell_key' => 'E', 'cell_width' => 15, 'value_key' => 'wiki_count'],
                    ['cell_title' => '评论数', 'cell_key' => 'F', 'cell_width' => 15, 'value_key' => 'comment'],
                    ['cell_title' => '点赞数', 'cell_key' => 'G', 'cell_width' => 15, 'value_key' => 'like'],
                    ['cell_title' => '收藏数', 'cell_key' => 'H', 'cell_width' => 18, 'value_key' => 'favorite'],
                    ['cell_title' => '评论+点赞+收藏', 'cell_key' => 'I', 'cell_width' => 18, 'value_key' => 'interact_num'],
                    ['cell_title' => '发布时间', 'cell_key' => 'J', 'cell_width' => 18, 'value_key' => 'publish_time'],
                    ['cell_title' => '更新时间', 'cell_key' => 'K', 'cell_width' => 18, 'value_key' => 'edittime'],
                    ['cell_title' => '质量', 'cell_key' => 'L', 'cell_width' => 15, 'value_key' => 'quality'],
                    ['cell_title' => '状态', 'cell_key' => 'M', 'cell_width' => 18, 'value_key' => 'status'],
                ];
            }
            $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            foreach ($sheetData as $row) {
                $sheet->setCellValue($row['cell_key'] . '1', $row['cell_title']);
                $sheet->getColumnDimension($row['cell_key'])->setWidth($row['cell_width']);
            }
            $rowNum = 2; // 从第二行开始
            foreach ($albumList as $info) {
                foreach ($sheetData as $row) {
                    $key = $row['value_key'];
                    $value = isset($info[$key]) ? $info[$key] : '';
                    switch ($key) {
                        case 'link':
                            $value = $this->copyUrl($info['album_id']);
                            break;
                        case 'publish_time':
                            $value = date('Y-m-d H:i:s', $value);
                            break;
                        case'comment':
                            $value = $AlbumCounters[$info['album_id']]['comment'];
                            break;
                        case 'like':
                            $value = $AlbumCounters[$info['album_id']]['like'];
                            break;
                        case 'favorite':
                            $value = $AlbumCounters[$info['album_id']]['favorite'];
                            break;
                        case 'quality':
                            $value = AlbumListModel::QUALITY_MAP[$value];
                            break;
                        case 'interact_num':
                            $value = $AlbumCounters[$info['album_id']]['comment'] + $AlbumCounters[$info['album_id']]['like'] + $AlbumCounters[$info['album_id']]['favorite'];
                            break;
                        case 'status':
                            $value = AlbumListModel::STATUS_MAP[$value];
                            break;
                    }
                    $cellKey = $row['cell_key'] . $rowNum;
                    if ($key == 'link') {
                        $sheet->setCellValue($cellKey, '清单详情');
                        $sheet->getCell($cellKey)->getHyperlink()->setUrl($value);
                        $sheet->getStyle($cellKey)->getFont()->getColor()->setARGB(\PhpOffice\PhpSpreadsheet\Style\Color::COLOR_BLUE);
                    } else {
                        $sheet->setCellValue($cellKey, $value);
                    }
                }
                $rowNum++;
            }
            $fileName = '清单列表' . date('YmdHis') . '.xlsx';
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="' . $fileName . '"');
            header('Cache-Control: max-age=0');
            header('Cache-Control: max-age=1');
            header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
            header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
            header('Pragma: public'); // HTTP/1.0
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');
        } catch (\Exception $exception) {
            Log::error('导出异常', $exception);
        }
    }

    private function getCondition($params)
    {
        if ($params['uid']) {
            $where['uid'] = $params['uid'];
        }
        if ($params['title']) {
            $where['title'] = $params['title'];
        }
        if ($params['score']) {
            $where['score'] = $params['score'];
        }
        if (isset($params['audit_status'])) {
            $where['status'] = $params['audit_status'];
        } else {
            $where['status'] = AlbumListModel::SHOW_STATUS_LIST;
        }
        if ($params['publish_time']['start'] && $params['publish_time']['end']) {
            $where['publish_time[>=]'] = strtotime($params['publish_time']['start']);
            $where['publish_time[<]'] = strtotime($params['publish_time']['end']);
        }
        if ($params['wiki_id']) {
            $wikiWhere = ['wiki_id' => $params['wiki_id'], 'status' => AlbumWikiListModel::STATUS_NORMAL];
            $albumIds = AlbumWikiListModel::selectByWhere($wikiWhere, 'album_id');
            $where['album_id'] = array_unique($albumIds);
        }
        if ($params['tag_name']) {
            $tagWhere = ['tag_name' => $params['tag_name'], 'status' => AlbumRelateTagsModel::STATUS_NORMAL];
            $albumIds = AlbumRelateTagsModel::selectByWhere($tagWhere, 'album_id');
            $where['album_id'] = array_unique($albumIds);
        }
        if ($params['album_id']) {
            $where['album_id'] = $params['album_id'];
        }
        $where['ORDER'] = ['edittime' => "DESC"];
        $page = $params['page'] ?: 1;
        $pageSize = $params['per_page'] ?: 20;
        $where['LIMIT'] = [($page - 1) * $pageSize, $pageSize];
        return $where;
    }

}